<template>
    <div class="recommend-detail" v-loading="loading">

        <div class="channel-detail">
            <div class="detail-left">
                <h3 class="title">推荐详情设置</h3>

                <el-form
                    label-position="left"
                    :model="detail"
                    :rules="rules"
                    ref="detail"
                    :hide-required-asterisk="true"
                    label-width="70px"
                    class="left-form input-no-border-box">
                    <el-form-item label="选择类别" prop="categoryIds">
                        <el-select
                            style="width:300px"
                            v-model="detail.categoryIds"
                            multiple
                            placeholder="请选择">
                            <el-option
                                v-for="item in typeList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="封面" prop="elementCover">
                        <UploadImg @change="uploadChange" v-model="detail.elementCover" :width="330" :height="486"/>
                    </el-form-item>

                    <el-form-item label="标题" prop="title">
                        <el-input v-model="detail.title" maxlength="10" placeholder="最多10个字"></el-input>
                    </el-form-item>

                    <!-- 富文本 -->
                    <div class="editor-box">
                        <!-- <uploadVideo @change="changeVideo" :noCover="true"  style="margin-bottom:10px;"/> -->

                        <div class="editor-tools">
                            <div class="editor-tools-items" @click="editorAddContent">
                                <el-tooltip class="item" effect="dark" content="添加内容文字" placement="top">
                                    <span class="edior-items-title">P</span>
                                </el-tooltip>
                            </div>

                            <div class="editor-tools-items" @click="editorAddTitle">
                                <el-tooltip class="item" effect="dark" content="添加标题" placement="top">
                                    <span class="edior-items-title">T</span>
                                </el-tooltip>
                            </div>

                            <div class="editor-tools-items" @click="editorAddSmallTitle">
                                <el-tooltip class="item" effect="dark" content="添加小标题" placement="top">
                                    <span class="edior-items-title">t</span>
                                </el-tooltip>
                            </div>

                            <div class="editor-tools-items" @click="editorAdddesc">
                                <el-tooltip class="item" effect="dark" content="添加描述" placement="top">
                                    <span class="edior-items-title">D</span>
                                </el-tooltip>
                            </div>

                            <div class="editor-tools-items" @click="editorAudioBox">
                                <el-tooltip class="item" effect="dark" content="添加音频背景盒子" placement="top">
                                    <span class="edior-items-title">B</span>
                                </el-tooltip>
                            </div>

                            <div class="editor-tools-items" @click="editorAudioBoxTitle">
                                <el-tooltip class="item" effect="dark" content="添加音频标题" placement="top">
                                    <span class="edior-items-title">bt</span>
                                </el-tooltip>
                            </div>

                            <div class="editor-tools-items">
                                <el-tooltip class="item" effect="dark" content="添加音频" placement="top">
                                    <el-upload
                                        class="avatar-uploader"
                                        action="/admin/file/uploadPic"
                                        :data="{
                                            needTransform: 1
                                        }"
                                        :show-file-list="false"
                                        accept=".mp3"
                                        :on-success="editorAddAudio">
                                        <div>
                                            <i class="el-icon-video-play"></i>
                                        </div>
                                    </el-upload>
                                </el-tooltip>
                            </div>

                            <div class="editor-tools-items">
                                <el-tooltip class="item" effect="dark" content="添加头图" placement="top">
                                    <el-upload
                                        class="avatar-uploader"
                                        action="/admin/file/uploadPic"
                                        :data="{
                                            needTransform: 1
                                        }"
                                        :show-file-list="false"
                                        accept=".jpg,.jpeg,.png,.gif"
                                        :on-success="editorAddImg">
                                        <div>
                                            <i class="el-icon-picture"></i>
                                        </div>
                                    </el-upload>
                                </el-tooltip>
                            </div>
                        </div>

                        <div id="editor"></div>
                    </div>

                    <el-form-item label="去体验">
                        <el-switch
                            @change="switchChange"
                            v-model="showSkin"
                            active-color="#13ce66">
                        </el-switch>
                    </el-form-item>

                    <el-form-item label="选择皮肤" prop="skinIds" v-if="showSkin">
                        <el-select
                            style="width:100%"
                            v-model="detail.skinIds"
                            :filter-method="getSkinList"
                            multiple
                            filterable
                            placeholder="请选择皮肤">
                                <el-option
                                    v-for="item in skinList"
                                    :key="item.id"
                                    :label="item.skinName"
                                    :value="item.id">
                                </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="投放时间" prop="">
                        <el-date-picker
                            v-model="detail._time"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                </el-form>
            </div>

            <div class="detail-right m-e-detail-box">
                <div class="right-fiexd">
                    <h3 class="title">样式展示</h3>
                    <div class="right-box">
                        <audio ref="audio" @ended="audioEnd" preload="none" crossorigin="anonymous"></audio>
                        <div v-html="detail.loadPage" contenteditable="false"></div>
                        <div class="m-e-go-experience-box" v-if="showSkin">
                            <div class="m-e-go-experience">去体验</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="tools">
            <el-button @click="goBack" class="btn">返回</el-button>
            <el-button type="success" class="btn save-btn" @click="saveRecommend" v-if="detail.id">保存</el-button>
            <el-button type="success" class="btn save-btn" @click="saveRecommend" v-else>新建</el-button>
        </div>
    </div>
</template>

<script>
import E from 'wangeditor'
import { formatDate } from '@/utils/utils'

export default {
    data () {
        return {
            detail: {
                categoryIds: [], // 分类id ,
                categoryName: '', // 类别名称 ,
                createTime: '', // 创建时间 ,
                elementCover: '', // 元素图片 ,
                endTime: '', // 结束时间 ,
                id: '', // 递增主键 ,
                loadPage: '', // 落地页 ,
                skinIds: [], // 皮肤id ,
                sort: '', // 排序 ,
                startTime: '', // 开始时间 ,
                status: '', // 0不展示 1展示 ,
                title: '', // 标题 ,
                updateTime: '', // 更新时间
                _time: []
            },
            showSkin: false,
            typeList: [],
            skinList: [],
            loading: false, // 详情加载loading
            rules: {
                categoryIds: [
                    { required: true, message: '请选择类别', trigger: 'change' }
                ],
                elementCover: [
                    { required: true, message: '请上传封面', trigger: 'change' }
                ],
                title: [
                    { required: true, message: '请填写标题', trigger: 'blur' }
                ],
                skinIds: [
                    { required: true, message: '请选择皮肤', trigger: 'change' }
                ]
            },

            currentAudio: {
                classList: {
                    remove: function () {},
                    contains: function () {}
                }
            }
        }
    },

    mounted () {
        this.getSkinList(null)
        this.getTypeList()
    },

    methods: {
        // 获取类别列表
        async getTypeList () {
            this.loading = true
            let res = await this.$http.get('/trade/selectActivityCategory', {
                params: {
                    pageNum: 1,
                    pageSize: 100
                }
            })
            if (res.code === '0') {
                this.typeList = res.data.list
                if (this.$route.query.id) {
                    this.getDetail()
                } else {
                    this.dataInit(this.detail)
                }
            } else {
                this.$message({
                    type: 'error',
                    message: res.desc
                })
                this.loading = false
            }
        },

        // 获取详情
        async getDetail () {
            let params = {
                id: this.$route.query.id
            }
            let res = await this.$http.get('/trade/selectActivityLoad', {
                params
            })
            if (res.code === '0' && res.data && res.data.length) {
                this.dataInit(res.data[0])
            } else {
                this.$message({
                    type: 'error',
                    message: res.desc
                })
                this.loading = false
            }
        },

        // 初始化数据
        dataInit (obj) {
            if (obj.skinIds && obj.id) {
                obj.skinIds = JSON.parse(obj.skinIds)
            } else {
                obj.skinIds = []
            }
            if (obj.skinIds && obj.skinIds.length) {
                this.showSkin = true
            }
            if (obj.startTime && obj.endTime) {
                obj._time = [obj.startTime, obj.endTime]
            } else {
                obj._time = []
            }
            this.$nextTick(() => {
                this.createEditor()
                this.audioBtnInit()
            })
            this.detail = obj
            this.loading = false
        },

        // 初始化富文本编辑器
        createEditor (item, index) {
            this.editor = new E('#editor')
            this.editor.customConfig.uploadImgServer = '/admin/file/uploadPic'
            this.editor.customConfig.uploadImgParams = {
            }
            this.editor.customConfig.colors = [
                '#1C74F4',
                '#ffffff',
                '#000000',
                '#eeece0',
                '#1c487f',
                '#4d80bf',
                '#c24f4a',
                '#8baa4a',
                '#7b5ba1',
                '#46acc8',
                '#f9963b'
            ]
            this.editor.customConfig.uploadFileName = 'file'
            this.editor.customConfig.uploadImgParams = {
                needTransform: 1
            }
            this.editor.customConfig.uploadImgHooks = {
                before: function (xhr, editor, files) {
                // 图片上传之前触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，files 是选择的图片文件
                // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
                // return {
                //     prevent: true,
                //     msg: '放弃上传'
                // }
                },
                success: function (xhr, editor, result) {
                // 图片上传并返回结果，图片插入成功之后触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
                },
                fail: function (xhr, editor, result) {
                // 图片上传并返回结果，但图片插入错误时触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
                },
                error: function (xhr, editor) {
                // 图片上传出错时触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
                },
                timeout: function (xhr, editor) {
                // 图片上传超时时触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
                },

                // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
                // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
                customInsert: function (insertImg, result, editor) {
                // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
                // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

                    // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
                    var url = result.data + '?x-oss-process=image/resize,w_360'
                    insertImg(url)

                // result 必须是一个 JSON 格式字符串！！！否则报错
                }
            }
            this.editor.customConfig.zIndex = 1
            this.editor.customConfig.menus = [
                // 'head', // 标题
                'bold', // 粗体
                // 'fontSize', // 字号
                // 'fontName', // 字体
                'italic', // 斜体
                'underline', // 下划线
                'strikeThrough', // 删除线
                'foreColor', // 文字颜色
                'backColor', // 背景颜色
                'link', // 插入链接
                // 'list', // 列表
                'justify', // 对齐方式
                // 'quote', // 引用
                // 'emoticon', // 表情
                'image', // 插入图片
                // 'table', // 表格
                // 'video', // 插入视频
                // 'code', // 插入代码
                'undo', // 撤销
                'redo' // 重复
            ]
            this.editor.customConfig.onchange = (html) => {
                // html 即变化之后的内容
                // if (!html.includes('padding:16px')) {
                //     html = `<div style="padding:16px 16px 0 16px;">${html}<div>`
                // }
                this.detail.loadPage = html
            }
            this.editor.create()
            this.editor.txt.html(this.detail.loadPage)
        },

        // 获取皮肤列表
        async getSkinList (val) {
            if (val === '') return
            let res = await this.$http.post('/trade/selectSkinData', {
                keyWord: val
            })
            if (res.code === '0') {
                this.skinList = res.data || []
            } else {
                this.$message({
                    type: 'error',
                    message: res.desc
                })
            }
        },

        // 上传封面成功
        uploadChange () {
            this.$refs.detail.validateField('elementCover')
        },

        // // 添加视频
        // changeVideo (url, duration, storageid, cover) {
        //     this.editor.cmd.do('insertHTML', `<iframe src="${url}" style="width:100%;" frameborder="0"></iframe>`)
        // },

        // 添加标题
        editorAddContent () { // h1
            this.editor.cmd.do('insertHTML',
            `<p>这是一段内容文字</p>`)
        },

        // 添加标题
        editorAddTitle () { // h1
            this.editor.cmd.do('insertHTML', `<h1 class="m-e-recommend-title">我是标题</h1>`)
        },

        // 添加小标题
        editorAddSmallTitle () { // h4
            this.editor.cmd.do('insertHTML', `<h4 class="m-e-recommend-small-title">我是小标题</h4>`)
        },

        // 添加描述
        editorAdddesc () { // h4
            this.editor.cmd.do('insertHTML', `<h4 class="m-e-recommend-img-desc">我是描述</h4>`)
        },

        // 添加音频背景盒子
        editorAudioBox () {
            this.editor.cmd.do('insertHTML',
            `<table class="m-e-audio-shadow-box" border="0" width="100%" cellpadding="0" cellspacing="0">
                <tbody><tr><th></th></tr></tbody>
            </table>`)
        },

        // 添加音频背景 标题
        editorAudioBoxTitle () { // h4
            this.editor.cmd.do('insertHTML', `<h4 class="m-e-audio-shadow-title">皮肤配音</h4>`)
        },

        // 添加音频
        editorAddAudio (res, file) { // h5
            if (res.code === '0') {
                this.editor.cmd.do('insertHTML', `
                    <h5 class="m-e-hidden" style="text-align:center;">-----音频不可编辑只可删除、点击播放----</h5>
                        <div class="m-e-audio-box" contenteditable="false">
                            <div class="audio-icon" data-src="${res.data}"></div>
                            <div class="addio-content" contenteditable="true"></div>
                            <div class="duration-box"></div>
                        </div>
                    <h5 class="m-e-hidden" style="text-align:center;">-----音频不可编辑只可删除、点击播放----</h5>
                `)
                this.audioBtnInit()
            } else {
                this.$message({
                    type: 'error',
                    message: res.desc
                })
            }
        },

        // 添加音频播放事件
        audioBtnInit () {
            let audioList = document.querySelectorAll('.m-e-audio-box')
            let audio = this.$refs.audio
            let _this = this
            for (let i = 0; i < audioList.length; i++) {
                let audioItem = audioList[i]
                // 图标
                let audioIcon = audioItem.querySelector('.audio-icon')
                // 右侧时长盒子
                let durationBox = audioItem.querySelector('.duration-box')
                let dAudio = document.createElement('audio')
                dAudio.src = audioIcon.getAttribute('data-src')
                dAudio.load()
                dAudio.oncanplay = function () {
                    let duration = dAudio.duration
                    durationBox.innerText = _this.timeInit(duration)
                    dAudio = null
                }
                audioIcon.onclick = function () {
                    if (audioItem.classList.contains('paly-audio')) {
                        _this.currentAudio.classList.remove('paly-audio')
                        audio.pause()
                        return
                    }
                    _this.currentAudio.classList.remove('paly-audio')
                    _this.currentAudio = audioItem
                    audioItem.classList.add('paly-audio')
                    let src = this.getAttribute('data-src')
                    audio.src = src
                    audio.play()
                }
            }
        },

        timeInit (val) {
            if (val) {
                let secondTime = parseInt(val)// 秒
                let minuteTime = 0// 分
                let hourTime = 0// 小时
                if (secondTime >= 60) { // 如果秒数大于60，将秒数转换成整数
                    // 获取分钟，除以60取整数，得到整数分钟
                    minuteTime = parseInt(secondTime / 60)
                    // 获取秒数，秒数取佘，得到整数秒数
                    secondTime = parseInt(secondTime % 60)
                    // 如果分钟大于60，将分钟转换成小时
                    if (minuteTime > 60) {
                        // 获取小时，获取分钟除以60，得到整数小时
                        hourTime = parseInt(minuteTime / 60)
                        // 获取小时后取佘的分，获取分钟除以60取佘的分
                        minuteTime = parseInt(minuteTime % 60)
                    }
                }
                secondTime = (secondTime + '').padStart(2, '0')
                let result = secondTime
                if (minuteTime >= 0) {
                    minuteTime = (minuteTime + '').padStart(2, '0')
                    result = minuteTime + ':' + result
                }
                if (hourTime > 0) {
                    result = parseInt(hourTime) + ':' + result
                }
                return result
            } else {
                return '00:01'
            }
        },

        // 音频播放完毕
        audioEnd () {
            this.currentAudio.classList.remove('paly-audio')
        },

        // 添加头图
        editorAddImg (res, file) { // h3
            if (res.code === '0') {
                this.editor.cmd.do('insertHTML', `<h3 class="m-e-banner"><img style="width:100%;" src="${res.data}" alt=""></h3>`)
            } else {
                this.$message({
                    type: 'error',
                    message: res.desc
                })
            }
        },

        // 返回上一页
        goBack () {
            this.$router.go(-1)
        },

        // 保存推荐
        saveRecommend () {
            this.$refs.detail.validate((valid) => {
                if (valid) {
                    this.saveRecommendFn()
                } else {
                    return false
                }
            })
        },

        switchChange (val) {
            if (!val) {
                this.detail.skinIds = []
            }
        },

        async saveRecommendFn () {
            if (this.loading) return
            let params = JSON.parse(JSON.stringify(this.detail))
            if (params._time && params._time.length >= 2) {
                params.startTime = params._time[0] ? (formatDate(params._time[0], 'YYYY-MM-DD') + ' 00:00:00') : ''
                params.endTime = params._time[1] ? (formatDate(params._time[1], 'YYYY-MM-DD') + ' 23:59:59') : ''
            }
            if (params.loadPage) {
               params.loadPage = params.loadPage.replace(/paly-audio/g, '')
            }
            // paly-audio
            delete params._time
            delete params.createTime
            delete params.updateTime
            params.skinIds = JSON.stringify(params.skinIds)
            this.loading = true
            let res = await this.$http.post('/trade/createActivityLoad', params)
            if (res.code === '0') {
                let message
                if (params.id) {
                    message = '修改成功！'
                } else {
                    message = '保存成功！'
                }
                this.$message({
                    type: 'success',
                    message
                })
                this.dataInit(res.data)
            } else {
                this.$message({
                    type: 'error',
                    message: res.desc
                })
            }
            this.loading = false
        }
    }
}
</script>

<style lang="scss" scoped>
    .channel-detail {
        display: flex;
        padding: 10px;
        .detail-left, .detail-right {
            .title {
                text-align: center;
            }
        }
        .detail-left {
            flex: 1;
            .left-form {
                margin-top: 10px;
            }
            .editor-box {
                margin-bottom: 10px;
            }

            .editor-tools {
                background-color: #f1f1f1;
                border: 1px solid #ccc;
                border-bottom: none;
                height: 32px;
                padding: 0 5px;
                display: flex;
                .editor-tools-items {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 32px;
                    cursor: pointer;
                    color: #999999;
                    &:hover .edior-items-title {
                        color: #000000;
                    }
                    &:hover i {
                        color: #000000;
                    }
                    .edior-items-title {
                        font-size: 20px;
                    }
                }
            }
        }
        .detail-right {
            width: 400px;
            .right-fiexd {
                width: 100%;
                position: sticky;
                top: 10px;
                left: 0;
                z-index: 1;
                .right-box {
                    border: 1px solid #ccc;
                    width: 362px;
                    margin: 0 auto;
                    height: 642px;
                    overflow: scroll;
                    padding-bottom: 76px;
                    > div {
                        border: none;
                    }
                }
            }
        }
    }
    .tools {
        margin-top: 20px;
        padding-bottom: 20px;
        display: flex;
        justify-content: center;
        .save-btn {
            margin-left: 200px;
        }
        .btn {
            width: 150px;
            padding: 10px;
        }
    }
</style>

<style lang="scss">
    .m-e-recommend-title {
        margin-top: 20px;
        padding: 0 16px;
        text-align: center;
        font-size:22px;
        font-family:SourceHanSansCN-Bold,SourceHanSansCN;
        font-weight:bold;
        color:rgba(28,32,44,1);
    }

    .m-e-recommend-small-title {
        padding: 0 16px;
        margin: 18px 0 12px;
        height:14px;
        font-size:14px;
        font-family:SourceHanSansCN-Medium,SourceHanSansCN;
        font-weight:700;
        color:rgba(28,32,44,.8);
    }

    .m-e-recommend-img-desc {
        margin-top: 6px;
        text-align: center;
        font-size:12px;
        font-family:SourceHanSansCN-Medium,SourceHanSansCN;
        font-weight:700;
        color:rgba(28,32,44,.6);
        &+p {
         margin-top: 16px;
        }
    }

    .m-e-audio-shadow-box {
        background:rgba(245,245,247,1);
        border-radius:8px;
        margin: 20px auto 0;
        padding: 16px 8px;
        border: none!important;
        width: calc(100% - 16px);
        font-size:14px;
        font-family:SourceHanSansCN-Regular,SourceHanSansCN;
        font-weight:400;
        color:rgba(28,32,44,1);
        th {
            font-size:14px!important;
            color:rgba(28,32,44,.8)!important;
            font-family:SourceHanSansCN-Regular,SourceHanSansCN!important;
            font-weight:400!important;
            border: none!important;
            text-align: left!important;
        }
        .m-e-recommend-img-desc  {
            margin-bottom: 12px;
        }
    }

    .m-e-audio-shadow-title {
        text-align: center;
        font-size:14px;
        font-family:SourceHanSansCN-Medium,SourceHanSansCN;
        font-weight:700;
        color:rgba(28,32,44,.8);
        margin-bottom: 10px;
    }

    .m-e-banner {
        width: 100%;
        height: 200px;
        overflow: hidden;
        > img {
            height: 100%;
            object-fit: cover;
            margin: 0!important;
        }
    }

    .m-e-audio-box {
        width: 328px;
        margin: 18px auto 0!important;
        padding-left: 12px!important;
        min-height: 40px;
        background:rgba(255,255,255,1);
        box-shadow:0px 2px 6px 0px rgba(214,214,214,0.5);
        border-radius:8px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        &.paly-audio {
            .audio-icon {
                background-image: url('//static-game.duodian.cn/html/image/audio-suspended.png');
            }
            .addio-content {
                color: #1C74F4;
            }
            .duration-box {
                color: #1C74F4;
            }
        }
        .audio-icon {
            width: 24px;
            height: 24px;
            margin-right: 14px;
            background-image: url('//static-game.duodian.cn/html/image/audio-play.png');
            background-size: 100% 100%;
        }
        .addio-content {
            flex: 1;
            padding: 10px 0;
            min-width: 100px;
            font-size:13px;
            font-family:SourceHanSansCN-Regular,SourceHanSansCN;
            font-weight:400;
            color:rgba(28,32,44,.4);
            text-align: center;
        }
        .duration-box {
            width: 50px;
            padding-right: 12px;
            text-align: right;
            font-size:12px;
            font-family:Roboto-Medium,Roboto;
            font-weight:700;
            color:rgba(28,32,44,.3);
        }
    }
    .m-e-go-experience-box {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height:60px;
        background-color: #ffffff;
        .m-e-go-experience {
            bottom: 0;
            margin: 10px 16px 0;
            height:44px;
            background:rgba(0,191,60,1);
            border-radius:4px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size:16px;
            font-family:SourceHanSansCN-Medium,SourceHanSansCN;
            font-weight:700;
            color:rgba(254,254,254,1);
        }
    }

    .m-e-detail-box {
        p {
            padding: 0 16px;
            line-height:24px;
            font-size:14px;
            font-family:SourceHanSansCN-Regular,SourceHanSansCN;
            font-weight:400;
            color:rgba(28,32,44,.8);
        }
        .m-e-hidden {
            display: none;
        }
        img {
            margin-top: 16px;
        }
    }
</style>
